"""
配置管理模块
负责加载和管理系统配置
"""
import os
import yaml
from typing import Dict, Any, Optional


class Config:
    """配置管理类"""
    
    def __init__(self, config_path: str = "config/settings.yaml"):
        self.config_path = config_path
        self._config = {}
        self.load_config()
    
    def load_config(self):
        """加载配置文件"""
        try:
            with open(self.config_path, 'r', encoding='utf-8') as f:
                self._config = yaml.safe_load(f)
        except FileNotFoundError:
            print(f"配置文件 {self.config_path} 不存在，使用默认配置")
            self._config = self._get_default_config()
        except Exception as e:
            print(f"加载配置文件失败: {e}")
            self._config = self._get_default_config()
    
    def get(self, key: str, default: Any = None) -> Any:
        """获取配置值"""
        keys = key.split('.')
        value = self._config
        
        for k in keys:
            if isinstance(value, dict) and k in value:
                value = value[k]
            elif isinstance(value, list) and k.isdigit():
                # 处理列表索引
                index = int(k)
                if 0 <= index < len(value):
                    value = value[index]
                else:
                    return default
            else:
                return default
        
        return value
    
    def set(self, key: str, value: Any):
        """设置配置值"""
        keys = key.split('.')
        config = self._config
        
        for k in keys[:-1]:
            if k.isdigit():
                # 处理列表索引
                index = int(k)
                if not isinstance(config, list):
                    config = []
                while len(config) <= index:
                    config.append({})
                config = config[index]
            else:
                if k not in config:
                    config[k] = {}
                config = config[k]
        
        # 处理最后一个键
        last_key = keys[-1]
        if last_key.isdigit():
            # 最后一个键是列表索引
            index = int(last_key)
            if not isinstance(config, list):
                config = []
            while len(config) <= index:
                config.append(None)
            config[index] = value
        else:
            # 最后一个键是字典键
            config[last_key] = value
    
    def save(self):
        """保存配置到文件"""
        try:
            os.makedirs(os.path.dirname(self.config_path), exist_ok=True)
            with open(self.config_path, 'w', encoding='utf-8') as f:
                yaml.dump(self._config, f, default_flow_style=False, allow_unicode=True)
        except Exception as e:
            print(f"保存配置文件失败: {e}")
    
    def _get_default_config(self) -> Dict[str, Any]:
        """获取默认配置"""
        return {
            'app': {
                'name': 'Tiny QA',
                'version': '1.0.0',
                'debug': True,
                'host': '0.0.0.0',
                'port': 5001
            },
            'database': {
                'type': 'sqlite',
                'path': 'data/database/tiny_qa.db'
            },
            'vector_db': {
                'type': 'chromadb',
                'path': 'data/vectors',
                'collection_name': 'documents'
            },
            'documents': {
                'path': 'data/documents',
                'supported_formats': ['.pdf', '.docx', '.xlsx', '.txt', '.md'],
                'chunk_size': 1000,
                'chunk_overlap': 200
            },
            'ai': {
                'embedding_model': 'sentence-transformers/all-MiniLM-L6-v2',
                'providers': []
            },
            'monitoring': {
                'file_watch': True,
                'scan_interval': 300,
                'auto_update': True
            },
            'logging': {
                'level': 'INFO',
                'file': 'logs/tiny_qa.log',
                'max_size': 10,
                'backup_count': 5
            }
        }


# 全局配置实例
config = Config() 